from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName

from polygonstudio.marvin import marvinMessageFactory as _

from plone.memoize import ram, instance, view
import re, anyjson, urllib2
from DateTime import DateTime
from time import time

import logging
logger = logging.getLogger('marvinview.py')

config = {}
config['moviepilot_api'] = 'a4b1b03795543b8e3bbfd774887d6cda'
config['tmdb_api'] = '9223ef7bbbb1003c4ad0bfd0cca46bda'
config['tmdb_language'] = 'de'







class IMarvinView(Interface):
    """
    Marvin view interface
    """

    def getMovieIdFromUrl():
        """
        """

    def getPersonIdFromUrl():
        """
	"""

    def getMovieTmdbIdFromId():
        """
        """
    def getMoviePostersFromTmdbId():
        """
	"""
    
    def getMovieInfos():
        """
        """

class MarvinView(BrowserView):
    """
    Marvin browser view
    """
    implements(IMarvinView)

    def __init__(self, context, request):
        self.context = context
        self.request = request

    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def portal(self):
        return getToolByName(self.context, 'portal_url').getPortalObject()

    def getMovieIdFromUrl(self, url):
        """
        collect movie info from tmdb.org with imdb original imdb url

        url = http://www.imdb.com/name/tt0001570/
        @return tt0001570
        """
	try:
            id = re.search('/(tt[0-9]{7})/', url()).group(1)
	    return id
        except AttributeError:
            logger.info("AttributeError: getMovieIdFromUrl %s, is maybe an invalid IMDB Movie Url" % url() )
            return ''

    def getPersonIdFromUrl(self, url):
        """
        get person's ID from a given IMDB url
        url = http://www.imdb.com/name/nm0001570/
        @return nm0001570
        """
	try:
            id = re.search('/(nm[0-9]{7})/', url()).group(1)
            return id
	except AttributeError:
	    logger.info("AttributeError: getPersonIdFromUrl %s, is maybe an invalid IMDB Person Url" % url() )
	    return ''

    # impossible, caching only works with plone/zope objects, or non-changing external objects
    # because the result of the function will be cached
    # @ram.cache(lambda *args: time() // (60 * 60))
    def getMovieTmdbIdFromId(self, id):
        """
        get TMDB movie id from a IMDB Id provided, data comes from http://themoviedb.org

        'http://api.themoviedb.org/2.1/Movie.imdbLookup/de/json/9223ef7bbbb1003c4ad0bfd0cca46bda/tt0137523'
        id = tt0137523
        @return 550
        """
	a = DateTime()

        url = 'http://api.themoviedb.org/2.1/Movie.imdbLookup/%s/json/%s/%s' % (config['tmdb_language'], config['tmdb_api'], id)
        request = urllib2.Request(url)
        response = urllib2.urlopen(request)
        response = anyjson.deserialize(response.read())[0]

        # for debug only
        b = DateTime()
        diff = b.millis() - a.millis()
        logger.info('TMDB.org Webservice Response Time for getMovieTmdbIdFromId(): %s ' % str(diff))

        return response['id']

    def getMoviePostersFromTmdbId(self, id):
        """
        get Posters from Movie from a TMDB ID given

        id = 550
        @return JSON
        """
        a = DateTime()
	url = 'http://api.themoviedb.org/2.1/Movie.getImages/%s/json/%s/%s' % (config['tmdb_language'], config['tmdb_api'], id)
        request = urllib2.Request(url)
        response = urllib2.urlopen(request)
        response = anyjson.deserialize(response.read())[0]
        #return response['posters'][0]['image']['type']
        posters = {}
        for poster in response['posters']:
            #if poster['image']['size'] == 'original' and poster['image']['height'] >= 1500:
	    if poster['image']['size'] == 'w154' and poster['image']['type'] == 'poster' and poster['image']['width'] == 154:
	        # for debug only
                b = DateTime()
                diff = b.millis() - a.millis()
                logger.info('TMDB.org Webservice Response Time for getMoviePostersFromTmdbId(): %s ' % str(diff))
                return poster['image']['url']
                #saveImagefromUrl(poster['image']['url'])
                #print 'unique url: ' + poster['image']['url']
            else:
	        #logger.info('No suitable poster image found!')
                pass
        #return 'Images saved'

    def saveImagefromUrl(self, url):
        """
        """
        response = urllib.urlopen(url)

        filename = url.split('/')[-1]
        mimetype = mimetypes.guess_type(filename)[0]

        im = cStringIO.StringIO(response.read()) # constructs a StringIO holding the image
        img = Image.open(im)

        #print img.format, img.size, img.mode
        #print filename
        #print mimetype
        img.save(filename)
        return filename

    def getMovieInfos(self):
        """
        get full movie info from imdb url
        """
        a = DateTime()
        #imdbId = self.context.getMovieIdFromUrl(url)
        #id = self.getMovieTmdbIdFromId(imdbId)
        url = 'http://api.themoviedb.org/2.1/Movie.getInfo/%s/json/%s/%s' % (config['tmdb_language'], config['tmdb_api'], self.context.tmdbId())
        request = urllib2.Request(url)
        response = urllib2.urlopen(request)
        b = DateTime()
        diff = b.millis() - a.millis()
        logger.info('TMDB.org Webservice Response Time for getMovieInfos(): '+ str(diff) )
        response = anyjson.deserialize(response.read())[0]
        #return response
	movieInfo = {}
	return 'foo test'
